<?php

namespace IDock\Insurance\AMIC\Request;

use Exception;
use IDock\Insurance\AMIC\AMICEnums;
use IDock\Insurance\AMIC\Request\AllAMICRequest;
use IDock\Insurance\AMIC\Response\UnderwritingResponse;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;
use IDock\Visitor\SpecialClausesVisitor;

class UnderwritingRequest extends AllAMICRequest
{
    public $requestType = 'N0204';

    protected $response = UnderwritingResponse::class;

    protected $urlTip = '提交核保';

    /*** @var  PremiumInquiryVisitor $visitor */
    protected $visitor;

    public function generate(): array
    {
        $arr = [
            'appBase' => [
                'orderNo' => $this->visitor->getExtInfoVisitor()->argc['orderNo'] ?? '',
                'appHealthIns' => 0,
            ],
            'applicant' => $this->getApplicant(),
            'appInsured' => $this->getInsured(),
            'appClauseList ' => $this->getSpecialList(),
            'elseInfo' => [
                'remark' => $this->visitor->getExtInfoVisitor()->underwriteMsg
            ]
        ];
        if($this->visitor->getNonCarUnderwritingVisitor()->getNonCarList()){
            $arr['appHealthIns'] = 1;
            $arr['appliHealthInsList'] = $this->getNonCarInfo();
        }
        return $arr;
    }

    private function getSpecialList()
    {
        $list = [];
        foreach ($this->visitor->getUnderwritingVisitor()->specialClausesList as $value){
            /**@var SpecialClausesVisitor $value * */
            $list[] = [
                'clauseCode' => $value->clauseCode,
                'context ' => $value->clauseContent,
                'clauseName ' => $value->clauseName,
                'clauseType ' => $value->clauseType,
            ];
        }
        return ['appClause' => $list];
    }

    private function getNonCarInfo()
    {
        $list = [];
        foreach ($this->visitor->getNonCarUnderwritingVisitor()->getNonCarList() as $value){
            /**@var NonCarProductVisitor $value*/
            $row = [
                'prodNo' => '0760',
                'effectiveDate' => $this->visitor->ciStartData ?: $this->visitor->biStartData,
                'expireDate' => $this->visitor->ciEndData ?: $this->visitor->biEndData,
                'productCode' => $value->planCode,
            ];
            $row['effectiveDate'] = date('YmdHi',strtotime($row['effectiveDate']));
            $row['expireDate'] = date('YmdHi',strtotime($row['expireDate']));
            $list[] = $row;
        }
        return $list;
    }

    private function getApplicant()
    {
        $model = $this->visitor->getApplicantVisitor();
        $arr = [
            'appName' => $model->name,
            'appType' => AMICEnums::$relationTypeCode[$model->typeCode] ?? '',
            'appNature' => $model->name == $this->visitor->getOwnerVisitor()->name ? '1' : '9',
            'certfCls' => AMICEnums::$certificateTypeCode[$model->certificateTypeCode] ?? '',
            'certfCode' => $model->certificateNo,
            'certfValidStartDate' => $model->certificateStartDate,
            'certfValidEndDate' => $model->certificateEndDate,
            'appMobile' => $model->mobile,
            'postCode' => $model->postcode,
            'appAddress' => $model->address,
            'appEmail' => $model->email,
            'province' => $model->provinceCode,
            'city' => $model->cityCode,
            'area' => $model->areaCode,
            'appNationality' => 'CHN',//默认中国
        ];
        if($arr['certfCls'] == '75'){
            $arr['legalRep'] = $model->linkManName;
        }
        if($model->typeCode == 'R1'){
            $arr['appBirthday'] = $this->getBirthday($model->certificateNo);
            $arr['appSex'] = $this->getGenderByIDcard($model->certificateNo);
        }
        return $arr;
    }

    private function getInsured()
    {
        $model = $this->visitor->getInsuredVisitor();
        $arr = [
            'insuredName' => $model->name,
            'insuredType' => AMICEnums::$relationTypeCode[$model->typeCode] ?? '',
            'insuredNature' => $model->name == $this->visitor->getOwnerVisitor()->name ? '1' : '9',
            'certfCls' =>  AMICEnums::$certificateTypeCode[$model->certificateTypeCode] ?? '',
            'certfCode' => $model->certificateNo,
            'certfValidStartDate' => $model->certificateStartDate,
            'certfValidEndDate' => $model->certificateEndDate,
            'insuredMobile' => $model->mobile,
            'postCode' => $model->postcode,
            'province' => $model->provinceCode,
            'city' => $model->cityCode,
            'area' => $model->areaCode,
            'insuredAddress' => $model->address,
            'insuredEmail' => $model->email,
            'insuredNationality' => 'CHN',//默认中国
        ];
        if($arr['certfCls'] == '75'){
            $arr['legalRep'] = $model->linkManName;
        }
        if($model->typeCode == 'R1'){
            $arr['insuredBirthday'] = $this->getBirthday($model->certificateNo);
            $arr['insuredSex'] = $this->getGenderByIDcard($model->certificateNo);
        }
        return $arr;
    }

    /**
     * 通过身份证获取性别
     * @param $idcard
     * @return int
     * @throws Exception
     */
    private function getGenderByIDcard($idCard){
        if(strlen($idCard) != 18){
            throw new Exception("身份证位数不合法");
        }
        $gender = intval(substr($idCard,16,1)) % 2;
        return $gender ? '1' : '2';
    }

    private function getBirthday($idCard)
    {
        if(strlen($idCard) != 18){
            throw new Exception("身份证位数不合法");
        }
        return substr($idCard,6,4).'-'.substr($idCard,10,2).'-'.substr($idCard,12,2);
    }


}
